package com.jeesite.modules.ic.service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.codec.Md5Utils;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.ic.service.wx.FileService;
import com.jeesite.modules.ic.service.wx.WxApiService;
import com.jeesite.modules.rt.entity.RtGroup;
import com.jeesite.modules.rt.service.RtGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.dao.IcUserDao;
import org.springframework.util.Base64Utils;

/**
 * 用户表Service
 * @author 李寒冰
 * @version 2024-06-21
 */
@Service
@Slf4j
public class IcUserService extends CrudService<IcUserDao, IcUser> {

	@Autowired
	private CatchService catchService;

	@Autowired
	private UserDataService userDataService;
    @Autowired
    private RtGroupService rtGroupService;
    @Autowired
    private WxApiService wxApiService;
    @Autowired
    private FileService fileService;



	/**
	 * 手机号登录
	 * @param icUser
	 * @return
	 */
	public IcUser login(IcUser icUser){
		IcUser byMobile = getByMobile(icUser.getMobile());
		if(byMobile!=null){
			icUser = byMobile;
		}
		return loginNew(icUser);
	}

	/**
	 * 登录新增用户
	 * @param icUser
	 * @return
	 */
	public IcUser loginNew(IcUser icUser){
		String randomNum = StringUtils.getRandomStr(6);
		icUser.setSalt(randomNum);
		String token = getToken(icUser.getMobile(), randomNum, icUser.getId());
		icUser.setToken(token);
		icUser.setLoginTime(new Date());
		if(StringUtils.isEmpty(icUser.getId())){
			icUser.setCreateTime(new Date());
		}
		if(StringUtils.isEmpty(icUser.getAvatarUrl())
				&& StringUtils.isNotEmpty(icUser.getAppWxOpenid())
			&& StringUtils.isNotEmpty(icUser.getAccessToken())){
			String appUserInfo = wxApiService.getAppUserInfo(icUser.getAppWxOpenid(), icUser.getAccessToken());
			log.info("用户信息:"+appUserInfo);
			JSONObject jsonObject = JSONObject.parseObject(appUserInfo);
			String nickname = jsonObject.getString("nickname");
			String headimgurl = jsonObject.getString("headimgurl");
			headimgurl = fileService.onLinePicSaveServer(headimgurl);
			icUser.setAvatarUrl(headimgurl);
			icUser.setNicheng(new String(nickname.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
		}
		if(StringUtils.isNotEmpty(icUser.getId())){
			icUser.setParentUserId(null);
		}
		save(icUser);
		if(StringUtils.isNotEmpty(icUser.getMobile())){
			String app_login_effective_time = Global.getConfig("app_login_effective_time");
			catchService.addHashCache("USERTOKEN",token, JSONObject.toJSONString(icUser),Integer.valueOf(app_login_effective_time), TimeUnit.HOURS);
		}
		return icUser;
	}

	public IcUser getByMobile(String mobile){
		IcUser icUser = new IcUser();
		icUser.setMobile(mobile);
		List<IcUser> list = this.findList(icUser);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	public IcUser getByAppWxOpenId(String appWxOpenId){
		IcUser icUser = new IcUser();
		icUser.setAppWxOpenid(appWxOpenId);
		List<IcUser> list = this.findList(icUser);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	public String getToken(String mobile,String salt,String userId){
		String str = mobile+salt+userId;
		String s = Base64Utils.encodeToString(str.getBytes());
		String token = Md5Utils.md5(s);
		return token;
	}

	public static void main(String[] args) {
		String s = Base64Utils.encodeToString("1111".getBytes());
		String token = Md5Utils.md5(s);
		System.out.println(token);
	}




	/**
	 * 获取单条数据
	 * @param icUser
	 * @return
	 */
	@Override
	public IcUser get(IcUser icUser) {
		return super.get(icUser);
	}


	public IcUser getOneUser(IcUser icUser) {
		List<IcUser> list = super.findList(icUser);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	public IcUser getOneUserByMobile(String mobile) {
		IcUser icUser = new IcUser();
		icUser.setMobile(mobile);
		List<IcUser> list = super.findList(icUser);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}




	/**
	 * 查询分页数据
	 * @param icUser 查询条件
	 * @param icUser page 分页对象
	 * @return
	 */
	@Override
	public Page<IcUser> findPage(IcUser icUser) {
		return super.findPage(icUser);
	}
	
	/**
	 * 查询列表数据
	 * @param icUser
	 * @return
	 */
	@Override
	public List<IcUser> findList(IcUser icUser) {
		return super.findList(icUser);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param icUser
	 */
	@Override
	@Transactional
	public void save(IcUser icUser) {



		super.save(icUser);

		// 新增用户，添加默认分组
		if(icUser.getIsNewRecord()){
			RtGroup rtGroup = new RtGroup();
			rtGroup.setUserId(icUser.getId());
			rtGroup.setName("默认分组");
			rtGroupService.save(rtGroup);
		}

	}
	
	/**
	 * 更新状态
	 * @param icUser
	 */
	@Override
	@Transactional
	public void updateStatus(IcUser icUser) {
		super.updateStatus(icUser);
	}
	
	/**
	 * 删除数据
	 * @param icUser
	 */
	@Override
	@Transactional
	public void delete(IcUser icUser) {
		super.delete(icUser);
	}
	
}